import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 扫描文件内容,查看是否包含字符
 */

public class Demo3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 获取指定目录
        System.out.print("请输入需要扫描的文件夹目录: ");
        String in = scanner.next();
        File inPath = new File(in);
        if(!inPath.isDirectory()) {
            System.out.println("目录非文件夹,程序终止");
            return;
        }
        // 获取指定字符
        System.out.print("请输入查找的字符: ");
        String word = scanner.next();
        List<String> list = new ArrayList<>();
        check(inPath,word,list);
        System.out.println("有" + list.size() + "个文件下包含 " + word);
        for(String str : list) {
            System.out.println(str);
        }
    }

    private static void check(File inPath, String word,List<String> list) {
        if(!inPath.isDirectory()) {
            byte[] ret = new byte[1024];
            int len = 0;

            try(FileInputStream read = new FileInputStream(inPath)) {
                while(true) {
                    len = read.read(ret);
                    if(len == -1) {
                        return;
                    }
                    if(new String(ret).contains(word)) {
                        list.add(inPath.getAbsolutePath());
                        return;
                    }
                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        File[] files = inPath.listFiles();
        for(File file:files) {
            check(file,word,list);
        }
    }
}
